<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="mini">
      <el-row :gutter="15">
        <div class="orderNo">退换货单号：{{ form.procudeReturnOdd }}</div>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="选择采购单" prop="procureOdd">
            <el-input v-model="form.procureOdd" :readonly="isReadOnly" class="input-with-select">
              <el-button slot="append" @click="isProcudeOpen = true">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库仓库" prop="wareId">
            <treeselect v-model="form.wareId" :normalizer="normalizer" :options="wareOptions" placeholder="请选择" @select="handleTreeSelectNode"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购人" prop="procurePersonName">
            <el-input v-model="form.procurePersonName" :disabled="true" placeholder="请输入"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话">
            <el-input v-model="form.procurePersonPhone" :disabled="true" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">采购商品</el-divider>
      <el-row>
        <el-table v-loading="loading" :data="form.procudeDetailsList" border>
          <el-table-column align="center" label="商品编号" prop="commodityNo"/>
          <el-table-column align="center" label="商品名称" prop="commodityName1"/>
          <el-table-column align="center" label="商品类别" prop="commodityTypeName"/>
          <el-table-column align="center" label="规格" prop="commoditySpec"/>
          <el-table-column align="center" label="单位" prop="unitName1"/>
          <el-table-column align="center" label="采购单价" prop="procurePrice">
            <template slot-scope="scope">
              <span>{{ formattedNumber(scope.row.procurePrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="采购数量" prop="procureNumber"/>
          <el-table-column align="center" label="退换方式" prop="returnType">
            <template slot-scope="scope">
              <el-select v-model="scope.row.returnType" placeholder="请选择">
                <el-option v-for="item in returnTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="退货数量" prop="commodityNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.commodityNumber" onkeyup="this.value = this.value.replace(/[^A-z0-9]/, '')"
                        type="number"
                        @input="calculateSubTotal(scope.row.commodityNumber, scope.row, 'commodityNumber')"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" size="mini" type="text" @click="handleDeleteProcudeDetails(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-divider content-position="left">退换商品
        <el-button :disabled="!form.wareId" icon="el-icon-plus" plain size="mini" style="margin-left:20px" type="primary" @click="handleAddCommodity">添加商品</el-button>
      </el-divider>
      <el-row>
        <el-table v-loading="loading" :data="form.procudeReturnDetailsList" border>
          <el-table-column align="center" label="商品编号" prop="commodityNo"/>
          <el-table-column align="center" label="商品名称" prop="commodityName1"/>
          <el-table-column align="center" label="商品类别" prop="commodityTypeName"/>
          <el-table-column align="center" label="规格" prop="commoditySpec"/>
          <el-table-column align="center" label="单位" prop="unitName1"/>
          <el-table-column align="center" label="单位关系" prop="unitRelationship"/>
          <el-table-column align="center" label="换算结果" prop="unitResult"/>
          <el-table-column align="center" label="库存数量" prop="wareCommodityNumber"/>
          <el-table-column align="center" label="成本单价" prop="costPrice">
            <template slot-scope="scope">
              <span>{{ formattedNumber(scope.row.unitResult * scope.row.costPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="退换数量" prop="commodityNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.commodityNumber" onkeyup="this.value = this.value.replace(/[^A-z0-9]/, '')" type="number" @input="calcNumber(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" size="mini" type="text"
                         @click="handleDeleteProcudeReturnDetails(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row :gutter="15" style="margin-top: 40px">
        <el-col :span="5">
          <el-form-item label="采购运费" prop="logisticsCost">
            <el-input v-model="form.logisticsCost" class="input-with-select" placeholder="请输入" type="number">
              <el-select slot="prepend" v-model="form.logisticsMethod" placeholder="请选择" style="width: 110px;">
                <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="其他费用" prop="otherCost">
            <el-input v-model="form.otherCost" class="input-with-select" placeholder="请输入" type="number">
              <el-select slot="prepend" v-model="form.otherMethod" placeholder="请选择" style="width: 110px;">
                <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="付款方式" prop="payType">
            <el-select v-model="form.payType" placeholder="请选择">
              <el-option v-for="item in payTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <div class="pay-amount-div">退货总额：<span class="">{{ formattedNumber(form.returnPrice) }}</span></div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单据备注" prop="remark">
            <el-input v-model="form.remark" :rows="4" placeholder="请输入单据备注" type="textarea"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer-options">
      <el-button type="primary" @click="submitForm()">提交审核</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 选择采购单 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isProcudeOpen" append-to-body title="选择采购单" width="800px">
      <el-form ref="queryProcudeForm" :inline="true" :model="queryProcudeParams" label-width="100px" size="small">
        <el-form-item label="采购单号" prop="procureNo">
          <el-input v-model="queryProcudeParams.procureNo" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleProcudeQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetProcudeQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="ErpProcudeList" @selection-change="handleSelectionChange" border>
        <el-table-column align="center" label="采购单号" prop="procureNo"/>
        <el-table-column align="center" label="采购人" prop="procurePersonName"/>
        <el-table-column align="center" label="采购金额" prop="payAmount">
          <template slot-scope="scope">
            <span>{{ formattedNumber(scope.row.payAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleSaleChange(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="procudeTotal > 0" :limit.sync="queryProcudeParams.pageSize" :page.sync="queryProcudeParams.pageNum" :total="procudeTotal"  @pagination="handleGetListProcude"/>
    </el-dialog>


    <!-- 选择商品 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isCommodityOpen" append-to-body title="选择商品" width="80%">
      <ErpCommodity v-if="isCommodityOpen" :notCommodityIds="notCommodityIds" :wareId="form.wareId" @SelectionChange="handleSelectionChange"></ErpCommodity>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedCommdity">确 定</el-button>
        <el-button @click="isCommodityOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getErpProcure, listErpProcure} from "@/api/erp/ErpProcure";
import {addErpProcudeReturn, getErpProcudeReturn, updateErpProcudeReturn} from "@/api/erp/ErpProcudeReturn";
import {listErpWareHouse} from "@/api/erp/ErpWareHouse";
import ErpCommodity from '@/views/erp/ErpCommodity/selectedCommodity'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {formattedNumber} from "@/utils/ruoyi";

export default {
  components: {
    ErpCommodity,
    Treeselect
  },
  props: [],
  dicts: ['erp_procure_batch', 'erp_logistics_stauts'],
  data() {
    return {
      // 分摊方式
      methodOptions: [
        {
          value: 1,
          label: '按重量分摊'
        }, {
          value: 2,
          label: '按体积分摊'
        }
      ],
      // 退货类型
      returnTypeOptions: [
        {
          value: 1,
          label: '退货'
        }, {
          value: 2,
          label: '退换'
        }
      ],
      // 收付款方式
      payTypeOptions: [
        {
          value: 1,
          label: '现金'
        }, {
          value: 2,
          label: '微信'
        }, {
          value: 3,
          label: '支付宝'
        }, {
          value: 4,
          label: '银行转账'
        }
      ],
      // 商品table loading
      loading: true,
      // 销售单列表
      ErpProcudeList: [],
      // 显示搜索条件
      showSearch: true,
      // 总记录条数
      procudeTotal: 0,
      // 采购单弹框
      isProcudeOpen: false,
      // 临时存放
      temporyList: [],
      // 选择商品弹框
      isCommodityOpen: false,
      // 仓库
      wareOptions: [],
      // 商品过滤
      notCommodityIds: [],
      // 是否只读
      isReadOnly: false,
      form: {},
      // 采购单搜索
      queryProcudeParams: {
        pageNum: 1,
        pageSize: 10,
        procureStatus: 2,
        procureNo: null,
      },
      rules: {
        procureOdd: [
          {required: true, message: "请选择采购单", trigger: "blur"}
        ],
      },
    }
  },
  computed: {
    calculateSubtotal() {
      let subtotalSum = 0;
      this.form.procudeDetailsList.forEach(item => {
        subtotalSum += parseFloat(!item.commodityNumber ? 0 : item.commodityNumber) * item.procurePrice;
      })
      return parseFloat(!this.form.logisticsCost ? 0 : this.form.logisticsCost) + parseFloat(!this.form.otherCost ? 0 : this.form.otherCost) + subtotalSum;
    }
  },
  watch: {
    'form.procudeDetailsList.subtotal': {
      handler(newVal) {
        this.form.returnPrice = this.calculateSubtotal
      },
      deep: true
    },
    'form.logisticsCost': {
      handler(newVal) {
        this.form.returnPrice = this.calculateSubtotal
      },
      deep: true
    },
    'form.otherCost': {
      handler(newVal) {
        this.form.returnPrice = this.calculateSubtotal
      },
      deep: true
    },
  },
  created() {
    this.reset();
    this.handleGetListProcude();
    this.getTreeselect();
    const procudeReturnId = this.$route.params && this.$route.params.procudeReturnId;
    if (procudeReturnId != 0 && procudeReturnId) {
      this.isReadOnly = true;
      this.getProcudeReturnInfo(procudeReturnId);
    } else {
      this.loading = false;
    }
  },
  methods: {
    formattedNumber,
    // 获取采购单列表
    handleGetListProcude() {
      this.loading = true;
      listErpProcure(this.queryProcudeParams).then(response => {
        this.ErpProcudeList = response.rows;
        this.procudeTotal = response.total;
        this.loading = false;
      })
    },
    getProcudeReturnInfo(saleId) {
      getErpProcudeReturn(saleId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.procudeDetailsList = [];
        this.form.procudeReturnDetailsList = [];
        response.data.detailsList.forEach(item => {
          if (item.returnCommodityType == 1) {
            this.form.payType = item.payType;
            this.form.procudeDetailsList.push(item);
          } else {
            this.form.procudeReturnDetailsList.push(item);
          }
        })
      });
    },
    // 采购单搜索
    handleProcudeQuery() {
      this.queryProcudeParams.pageNum = 1;
      this.handleGetListProcude();
    },
    /** 重置按钮操作 */
    resetProcudeQuery() {
      this.resetForm("queryProcudeForm");
      this.handleProcudeQuery();
    },
    /** 转换仓库管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.wareId,
        label: node.wareName,
        children: node.children
      };
    },
    /** 查询仓库管理下拉树结构 */
    getTreeselect() {
      listErpWareHouse().then(response => {
        this.wareOptions = this.handleTree(response.data, "wareId", "warePid");
      });
    },
    // 表单重置
    reset() {
      this.form = {
        procudeReturnId: null,
        procudeReturnOdd: 'CG' + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}'),
        procureId: null,
        procureOdd: null,
        wareId: null,
        returnPrice: null,
        remark: null,
        logisticsCost: null,
        logisticsMethod: 1,
        otherCost: null,
        otherMethod: 1,
        paymentMethod: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null,
        approveStatus: null,
        approveId: null,
        approveName: null,
        approveTime: null,
        rejectTime: null,
        rejectReason: null,
        payType: null,
        detailsList: [],
        procudeDetailsList: [],
        procudeReturnDetailsList: []
      };
      this.resetForm("form");
    },
    // 采购单选择
    handleSaleChange(row) {
      this.form.procureOdd = row.procureNo;
      this.form.procureId = row.procureId;
      this.form.procurePersonName = row.procurePersonName;
      this.form.procurePersonPhone = row.procurePersonPhone;
      this.form.procudeDetailsList = [];
      this.form.procudeReturnDetailsList = [];
      // 根据所选择的采购单加载对应商品
      getErpProcure(row.procureId).then(res => {
        res.data.detailsList.forEach(item => {
          this.form.procudeDetailsList.push({
            commodityId: item.commodityKey,
            commodityName1: item.supplierCommodityName,
            commodityNo: item.supplierCommodityNo,
            commodityTypeName: item.supplierCommodityType,
            commoditySpec: item.supplierCommoditySpec,
            unitName1: item.supplierCommodityUnit,
            procurePrice: item.procurePrice,
            procureNumber: item.procureNumber,
            commodityNumber: item.commodityNumber,
            orderOdd: this.form.procudeReturnOdd,
            returnCommodityType: 1,
            subtotal:item.subtotal,
            orderType: 1,
            returnType: 1,
          })
        })
        this.isProcudeOpen = false;
        // 重新计算退货总额
        this.calculateSubTotal();
      })
    },
    // 仓库选择
    handleTreeSelectNode(e) {
      this.form.wareId = e.wareId;
    },
    // 选择商品
    handleAddCommodity() {
      //this.notCommodityIds = this.form.procudeDetailsList.map(item => item.commodityId);
      this.notCommodityIds = this.form.procudeReturnDetailsList.map(item => item.commodityId);
      this.isCommodityOpen = true;
    },
    // 提交数据
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.detailsList = this.form.procudeDetailsList.concat(this.form.procudeReturnDetailsList)
          if (this.form.procudeReturnId != null) {
            updateErpProcudeReturn(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              const obj = {path: "/psi/warehouse/ErpProcudeReturn", name: "ErpProcudeReturn"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          } else {
            addErpProcudeReturn(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              const obj = {path: "/psi/warehouse/ErpProcudeReturn", name: "ErpProcudeReturn"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          }

        }
      });
    },
    // 审核
    handleAudit(type) {
      this.form.approveStatus = type;
      auditErpSaleReturn(this.form).then(res => {
        this.$modal.msgSuccess("操作成功");
        const obj = {path: "/psi/outStock/ErpSaleReturn", name: "ErpProcudeReturn"};
        this.$tab.closeOpenPage(obj);
        this.$tab.refreshPage(obj);
      })
    },
    // 取消
    cancel() {
      const obj = {path: "/psi/warehouse/ErpProcudeReturn", name: "ErpProcudeReturn"};
      this.$tab.closeOpenPage(obj);
      this.$tab.refreshPage(obj);
    },
    // 商品选择
    handleSelectionChange(selection) {
      this.temporyList = selection;
    },
    // 确定选择商品
    submitSelectedCommdity() {
      this.temporyList.forEach(item => {
        this.form.procudeReturnDetailsList.push({
          ...item,
          orderOdd: this.form.procudeReturnOdd,
          orderType: 1,
          returnCommodityType: 2,
          commodityNumber: 1,
        })
      })
      this.isCommodityOpen = false;
    },
    // 根据对象删除数组
    handleDeleteProcudeDetails(row) {
      const index = this.form.procudeDetailsList.indexOf(row);
      if (index > -1) {
        this.form.procudeDetailsList.splice(index, 1);
      }
      // 重新计算退货总额
      this.calculateSubTotal();
    },
    handleDeleteProcudeReturnDetails(row) {
      const index = this.form.procudeReturnDetailsList.indexOf(row);
      if (index > -1) {
        this.form.procudeReturnDetailsList.splice(index, 1);
      }
    },
    /** 计算小计 */
    calculateSubTotal(v, row, field) {
      if (v) {
        row[field] = v;
      }
      if(row.commodityNumber > row.procureNumber){
        this.$modal.msgError("商品编号["+row.commodityNo+"]退换货数量不能大于销售数量!");
        row.commodityNumber = row.procureNumber;
      }
      if(row.commodityNumber < 1){
        this.$modal.msgError("商品编号["+row.commodityNo+"]退换货数量不能小于销售数量!");
        row.commodityNumber = 1;
      }
      if (row) {
        row.subtotal = parseFloat(!row.commodityNumber ? 0 : row.commodityNumber) * parseFloat(!row.procurePrice ? 0 : row.procurePrice);
      }
      this.form.payAmount = 0;
      let subtotalSum = 0;
      this.form.procudeDetailsList.forEach((item) => {
        subtotalSum += parseFloat(!item.subtotal ? 0 : item.subtotal);
      });
      this.form.returnPrice = parseFloat(!this.form.logisticsCost ? 0 : this.form.logisticsCost) + parseFloat(!this.form.otherCost ? 0 : this.form.otherCost) + subtotalSum;
    },
    /** 数值累计 */
    numberSum(list) {
      let sum = 0;
      list.forEach(i => {
        sum += i.commodityNumber;
      })
      return sum;
    },
    /** 数值限制 */
    calcNumber(row){
      if(row.commodityNumber < 1){
        this.$modal.msgError("商品编号["+row.commodityNo+"]退换数量不能小于1!");
        row.commodityNumber = 1
      }
    }
  }
}

</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
